import java.util.ArrayList;
import java.util.List;

import model.Device;
import model.Group;
import model.Message;
import model.User;


public class Controller {
	private WorkQueue wq;
	private SendMessage sm;
	private DAO db;
	
	public Controller(){
		wq = new WorkQueue();
		sm = new SendMessage(wq);
		sm.start();
		db = new DAO();
	}
	
	public synchronized void stop(){
		sm.stop();
	}
	
	public synchronized boolean addOrUpdateDevice(String deviceId, String deviceKey){
		int index = db.addOrUpdateDevice(deviceId, deviceKey);
		if(index > -1)
			return true;
		return false;
	}
	
	public synchronized boolean setUserOnDevice(String username, String deviceId){
		Device d = db.getDeviceByDeviceId(deviceId);
		if(d == null)
			return false;
		
		User u = db.getUserByName(username);
		if(u == null){
			int uId = db.addUser(username, 0, 0, d.getId());
			u = db.getUserById(uId);
			return u != null;
		}
		
		u.setDeviceId(d.getId());
		return db.updateUser(u);
	}
		
	public synchronized boolean updateUserScore(String username, int win, int lost){
		if(win == 0 && lost == 0)
			return false;
		User u = db.getUserByName(username);
		if(u == null)
			return false;
		u.setWin(u.getWin() + win);
		u.setLost(u.getLost() + lost);
		
		if(!db.updateUser(u))
			return false;
		List<Group> gList = db.getGroupsThatUserIsPartIn(u);
		
		for(int i = 0; i < gList.size(); i++){
			List<User> uList = db.getUsersInGroup(gList.get(i).getId());
			
			for(int k = 0; k < uList.size(); k++){
				Device d = db.getDeviceById(uList.get(k).getDeviceId());
				if(d != null){
					Message m = new Message();
					m.setRegistrationId(d.getDeviceKey());
					m.setMessage("You got Mail!");
					wq.addWork(m);
				}
			}	
		}
		
		return true;
	}
	
	public synchronized boolean addUserToGroup(String username, String groupname){
		User u = db.getUserByName(username);
		if(u == null)
			return false;
		
		int id = db.getGroupIdFromName(groupname);
		
		if(id == -1){
			id = db.addGroup(groupname);
		}
		if(id != -1)
			return db.addUserToGroup(u.getId(), id);
		return false;
	}
	
	public synchronized List<User> getGroupScore(String groupname, int top){
		int id = db.getGroupIdFromName(groupname);
		
		if(id == -1)
			return new ArrayList<User>();
		
		return db.getTopNUsersFromGroup(top, id);
	}
	
	public List<Group> getGroupsUserIsMemberIn(String username) {
		User u = db.getUserByName(username);
		if(u == null)
			return new ArrayList<Group>();
		return db.getGroupsThatUserIsPartIn(u);
	}
	
	public synchronized void test(String deviceId){
		Device d = db.getDeviceByDeviceId(deviceId);
		if(d != null){
			Message m = new Message();
			m.setRegistrationId(d.getDeviceKey());
			m.setMessage("You got Mail!");
			wq.addWork(m);
		}else{
			System.out.println("failed to retrive device info");
		}
	}

	
	
	
	
	

}
